package com.neusoft.neu24.service.impl;

import com.neusoft.neu24.Result.CommonResult;
import com.neusoft.neu24.entity.Sysnode;
import com.neusoft.neu24.mapper.SysnodeMapper;
import com.neusoft.neu24.service.ISysnodeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysnodeServiceImpl implements ISysnodeService {
    @Resource
    private SysnodeMapper mapper;

    @Override
    public CommonResult<Sysnode> loadNode() {
        List<Sysnode> list = mapper.listAll();
        Sysnode root =  list2Tree(list);
        return CommonResult.success(root);
    }



    private Sysnode list2Tree(List<Sysnode> sysnodes) {
//        1、寻找根节点
        Sysnode root = null ;
        for (Sysnode sysnode : sysnodes) {
            if(sysnode.getPid() == null){
                root =  sysnode;
                break;
            }
        }

//        填充根节点的孩子
        fillChildren( root , sysnodes );

        return   root;

    }

    private void fillChildren(Sysnode root, List<Sysnode> sysnodes) {
        if (root == null || sysnodes == null || sysnodes.size() == 0) {
            return;
        }
        if (root.getChildren() == null) {
            root.setChildren(new ArrayList<Sysnode>());
        }

        for (Sysnode sysnode : sysnodes) {
            if (sysnode.getPid() != null && sysnode.getPid().intValue() == root.getId().intValue()) {
                root.getChildren().add(sysnode);
            }
        }
//        递归填充孩子节点
        if (root.getChildren() == null ||  root.getChildren().size()== 0){
            return;
        }

        for (Sysnode sysnode : root.getChildren()) {
            fillChildren(sysnode, sysnodes);
        }
    }
}
